import re
import sys
import argparse
from datetime import datetime

# Parse.py
# 用法: python Parse.py path/to/logfile [--threshold 5]
# 从日志中提取形如 [YYYY-MM-DD HH:MM:SS.mmm] 的时间戳，比较相邻时间点的差异，
# 如果间隔超过阈值（秒）则输出相关日志行和间隔信息。
# 空白行会被过滤掉（不会作为事件处理）。

TS_RE = re.compile(r'\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{1,6})\]')

def parse_file(path):
    if path == '-':
        lines = sys.stdin.read().splitlines()
    else:
        with open(path, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.read().splitlines()
    events = []  # list of (line_no, datetime, line_text)
    for ln, line in enumerate(lines, start=1):
        # 过滤仅包含空白的空行
        if not line.strip():
            continue
        for m in TS_RE.finditer(line):
            ts_text = m.group(1)
            # datetime expects microseconds; allow 1-6 digits and normalize
            if '.' in ts_text:
                base, frac = ts_text.rsplit('.', 1)
                frac = (frac + '000000')[:6]
                ts_text_norm = base + '.' + frac
            else:
                ts_text_norm = ts_text + '.000000'
            try:
                ts = datetime.strptime(ts_text_norm, '%Y-%m-%d %H:%M:%S.%f')
            except ValueError:
                continue
            events.append((ln, ts, line.rstrip()))
    return events

def report_gaps(events, threshold):
    if not events:
        print("未找到日志事件。")
        return
    
    gap_count = 0
    print(f"正在分析日志，时间差阈值: {threshold}秒...\n")
    
    for i in range(len(events)-1):
        prev_ln, prev_ts, prev_line = events[i]
        curr_ln, curr_ts, curr_line = events[i+1]
        delta = (curr_ts - prev_ts).total_seconds()
        
        if abs( delta) > threshold:
            gap_count += 1
            print(f"发现异常时间差 #{gap_count}: {delta:.3f}秒 > {threshold}秒")
            print(f"  位置: 行 {prev_ln} -> 行 {curr_ln}")
            print(f"  前一条日志: [{prev_ts.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}] {prev_line}")
            print(f"  后一条日志: [{curr_ts.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}] {curr_line}")
            print("-" * 80)
    
    print(f"\n总结: 共发现 {gap_count} 处时间差超过 {threshold} 秒")
    if gap_count > 0:
        print(f"首次异常在行 {events[0][0]}-{events[1][0]}")
        print(f"末次异常在行 {events[-2][0]}-{events[-1][0]}")

def main():
    p = argparse.ArgumentParser(description='查找日志中相邻时间戳间隔超过阈值的记录')
    p.add_argument('logfile', nargs='?', default='-', help='日志文件路径，或 - 从 stdin 读取')
    p.add_argument('--threshold', '-t', type=float, default=5.0, help='阈值（秒），默认 5 秒')
    args = p.parse_args()

    events = parse_file(args.logfile)
    report_gaps(events, args.threshold)

if __name__ == '__main__':
    main()